package com.culture.bootdemo.utils;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author wen
 * @date 2019/12/30 20:32
 * @Description 使用的时候，直接 CurrentTimeMillisClock.getInstance().now()就可以了。
 **/
public class CurrentTimeMillisClock {

    private volatile long now;

    private CurrentTimeMillisClock() {
        this.now = System.currentTimeMillis();
        scheduleTick();
    }

    private void scheduleTick() {
        new ScheduledThreadPoolExecutor(1, runnable -> {
            Thread thread = new Thread(runnable, "current-time-millis");
            thread.setDaemon(true);
            return thread;
        }).scheduleAtFixedRate(() ->
                        now = System.currentTimeMillis()
                , 1, 1, TimeUnit.MILLISECONDS);
    }

    public long now() {
        return now;
    }

    public static CurrentTimeMillisClock getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private static class SingletonHolder {
        private static final CurrentTimeMillisClock INSTANCE = new CurrentTimeMillisClock();
    }

    public static void main(String[] args) {
        long now = CurrentTimeMillisClock.getInstance().now;
        System.out.println(now);
        System.out.println(System.currentTimeMillis());

        System.out.println(Integer.MAX_VALUE);
        System.out.println(Long.MAX_VALUE);
        System.out.println(Long.MAX_VALUE - Integer.MAX_VALUE);
    }


}
